﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using SampleTargetService;
using System.Collections.Concurrent;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace ParallelCacheHandler.UnitTest
{
    [TestClass]
    public class ParallelTest
    {
        /// <summary>
        /// We are attempting to hit the same service multiple times with the same parameter. 
        /// the Unity Interceptor 
        /// </summary>
        [TestMethod]
        public void MainTest()
        {
            var _container = new UnityContainer();
            _container.LoadConfiguration();

            //ICustomerService is configured in unity to use interception and the Parallel cache
            var service = _container.Resolve<ICustomerService>();

            var ids = new List<int>() { 1, 2, 2, 2, 3, 3 };
            var bag = new ConcurrentBag<Customer>();

            //execute the requests in parallel
            Parallel.ForEach(ids, item => bag.Add(service.GetCustomer(item)));

            var distinctIds = ids.Distinct();
            foreach (var id in distinctIds)
            {
                //ensure that each of the results for the id has the same timestamp. i.e. : retrieved from the cache
                var results = bag.Where(i => i.Id == id);
                foreach (var result in results)
                {
                    Assert.AreEqual(results.First().Timestamp, result.Timestamp);
                }
            }

            //ensure that different ids are producing different results. i.e: the cache is able to differentiate by parameters
            Assert.AreNotEqual(bag.Where(i => i.Id == 1).First().Timestamp,
                bag.Where(i => i.Id == 2).First().Timestamp);

            Assert.AreNotEqual(bag.Where(i => i.Id == 1).First().Timestamp,
                bag.Where(i => i.Id == 3).First().Timestamp);

            Assert.AreNotEqual(bag.Where(i => i.Id == 2).First().Timestamp,
                bag.Where(i => i.Id == 3).First().Timestamp);
        }
    }
}
